<style></style>
<template>
  <!-- 头部搜索 -->
  <div style="margin-bottom: 10px;">
    <span style="margin-right: 10px;">角色名称:</span>
    <el-input v-model="searchText" style="width: 240px;margin-right: 10px;" placeholder="请输入角色名称" />
    <el-button :icon="Search" type="primary" @click="btnSearch()" plain>搜索</el-button>
    <!-- 打开添加弹窗 -->
    <el-button type="success" @click="Add()" plain>
      <el-icon>
        <Plus />
      </el-icon>添加
    </el-button>
  </div>

  <!-- 表格 -->
  <!-- 设置表格中的语言配置为中文 -->
  <el-config-provider :locale="zhCn">
    <el-table :data="tableData" row-key="Roleid" style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column label="角色编号" prop="Roleid" align="center" />
      <el-table-column label="角色名称" prop="Rolename" align="center" />
      <el-table-column label="用户状态" prop="Rolestate">
        <template #default="scope">
          <el-tag :type="scope.row.Rolestate ? 'primary' : 'success'">{{ scope.row.Rolestate ? "启用" : "不启用" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" @click="editPermission(scope.$index, scope.row)" plain>编辑权限</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="warning" :icon="Edit" size="small" @click="handleEdit(scope.$index, scope.row)"
            plain>编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.$index, scope.row)"
            plain>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block" style="margin-top: 10px;">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50, 100]"
        :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </el-config-provider>

  <!-- 添加/编辑Form -->
  <el-config-provider :locale="zhCn">
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" :destroy-on-close="true"
      :before-close="clearForm">
      <el-form :model="form" :rules="rules" ref="ruleFormRef" status-icon :label-position="labelPosition"
        class="demo-form-inline">

        <!-- 投诉标题 -->
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="Rolename">
          <el-input v-model="form.Rolename" placeholder="请输入投诉标题" autocomplete="off" />
          <span>注：新角色权限为空，需另外编辑</span>
        </el-form-item>

        <!-- 状态-->
        <el-form-item label="用户状态" :label-width="formLabelWidth" prop="Rolestate">
          <el-switch v-model="form.Rolestate" class="ml-2" inline-prompt active-text="启用" inactive-text="不启用" />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearForm">取消</el-button>
          <el-button type="primary" @click="btnSave(ruleFormRef)">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-config-provider>

  <!-- 编辑角色权限 -->
  <el-config-provider :locale="zhCn">

    <el-drawer v-model="drawer" title="编辑用户权限" :with-header="true" :before-close="handleClose">

      <el-table ref="multipleTableRef" :data="treeDate" row-key="id" border stripe style="width: 100%;"
        @selection-change="handleSelectionChanges">
        <el-table-column type="selection" width="55" />
        <el-table-column label="名称" prop="name" />
      </el-table>

      <el-button @click="clearForm">取消</el-button>
      <el-button type="primary" @click="btnSaves(0, 0)">
        保存
      </el-button>

    </el-drawer>
  </el-config-provider>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'
import { ElTable } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElDrawer } from 'element-plus'



//存储表格数据信息
let tableData = ref([]);
let treeDate = ref([]);

//搜索信息
var searchText = ref("");

//控制打开/关闭模态框
const dialogFormVisible = ref(false)
//表单输入框前标题宽度
const formLabelWidth = '100px'
//弹出层标题
var dialogTitle = ref("")


//编辑权限抽屉弹出
const drawer = ref(false)

onMounted(() => {
  bindData(currentPage.value, pageSize.value, searchText.value);

})



//编辑权限按钮
const editPermission = (index, row) => {
  console.log(row.Roleid);
  drawer.value = true;
  axios.get('https://localhost:7090/api/JurisdictionManage?roleid=' + row.Roleid)
    .then(res => {
      treeDate.value = res.data;
      //console.log("tree", treeDate.value)
      toggleSelection(treeDate.value);
    })
}


const multipleTableRef = ref(null)
const multipleSelection = ref([])
const idArr = ref([])

const toggleSelection = (rows) => {
  if (rows) {
    console.log(rows);
    rows.forEach((row) => {
      if (row.ELE_CHECKED == true) {  //单个情况回显
        // if (ids.includes(row.id)) { // 判断当前行是否为默认回显行  数组多个数据回显情况
          console.log("rol",row.ELE_CHECKED);
          this.$refs.multipleTable.toggleRowSelection(row, true); // 默认勾选
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true); // 不选中
      }
    })
    // if (rows.ELE_CHECKED == true) {  //单个情况回显

    //   // if (ids.includes(row.id)) { // 判断当前行是否为默认回显行  数组多个数据回显情况
    //   multipleTableRef.value.toggleRowSelection(rows, true) // 默认勾选
    // } else {
    //   multipleTableRef.value.toggleRowSelection(rows, false) // 不选中
    // }
  } else {
    multipleTableRef.value.clearSelection()
  }
}
const handleSelectionChanges = (val) => {
  multipleSelection.value = val
  idArr.value = val.map(item => item.id)
  console.log(idArr.value)
  console.log(multipleSelection.value)
}

function btnSaves() {

}

//存储表单数据
var form = ref({
  Roleid: 0,
  Rolename: '',
  Rolestate: true
})

function Add() {
  dialogTitle.value = "添加角色";
  dialogFormVisible.value = true;
}

const handleEdit = (index, row) => {
  console.log(row)
  dialogTitle.value = "修改投诉";
  dialogFormVisible.value = true;
  form.value = row;
}

function btnSave(formEl) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios({
        method: form.value.Roleid > 0 ? 'put' : 'post',
        data: form.value,
        url: 'https://localhost:7090/api/RoleInfo',
        headers: { 'Content-Type': 'application/json' }
      }).then((res) => {
        if (res) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          clearForm()
          bindData(currentPage.value, pageSize.value, searchText.value);
        } else {
          ElMessage({
            message: '保存失败',
            type: 'error',
          })
        }
      }).catch((err) => {
        ElMessage({
          message: err,//"网络异常，请联系管理员!!!"
          type: 'error',
        })
      })
    } else {
      return false
    }
  })
}

//验证
const ruleFormRef = ref();
//添加表单校验
const rules = reactive({
  Rolename: [{
    required: true,//必填
    message: '请输入角色名称',
    trigger: 'change'
  }]
})


//删除
var handleDelete = (index, row) => {
  var roleid;
  ElMessageBox.confirm(
    '确定要删除吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    roleid = row.Roleid;
    axios.delete(`https://localhost:7090/api/RoleInfo/?roleid=${roleid}`)
      .then(function (res) {
        if (res.data == true) {
          ElMessage({
            type: 'success',
            message: "删除成功"
          })
          clearForm()
          bindData(currentPage.value, pageSize.value, searchText.value);
        } else {
          ElMessage({
            type: 'warning',
            message: "删除失败" + res.data.msg
          })
        }
      }).catch(() => {
        ElMessage({
          type: 'warning',
          message: "删除失败!"
        })
      })

  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '用户取消操作',
    })
  })
}

//绑定数据表格
function bindData(page, limit, rolename) {
  axios.get(`https://localhost:7090/api/RoleInfo?page=${page}&limit=${limit}&rolename=${rolename}`)
    .then(function (response) {
      console.log(response.data);
      tableData.value = response.data.data;
      total.value = response.data.total;
    })
}

//模糊查询
function btnSearch() {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

//清除表单
function clearForm() {
  dialogFormVisible.value = false;
  form.value = {
    Roleid: 0,
    Rolename: '',
    Rolestate: true
  };
}

//分页
const currentPage = ref(1)//当前页数
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const pageSize = ref(5)//每页条数
const total = ref(0)//总数据量

//切换每页条数
const handleSizeChange = (val) => {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

//切换页数
const handleCurrentChange = (val) => {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

</script>